package com.study.experiment04.servlet;

import com.study.experiment04.entity.UserP;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@WebServlet(name = "login", urlPatterns = "/experiment04/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("LoginServlet");
        request.setCharacterEncoding("UTF-8");
        PreparedStatement statement;
        UserP user = new UserP();
        user.setName(request.getParameter("name"));
        user.setPwd(request.getParameter("pwd"));
        Connection conn;
        try {
            String msg = "";
            String url = "jdbc:mysql://localhost:3306/servletdemo?serverTimezone=CTT&useUnicode=true&characterEncoding=utf-8&allowMultiQueries=true";
            String userName = "root";
            String password = "123456";
            Class.forName("com.mysql.jdbc.Driver");
            // 建立连接
            conn = DriverManager.getConnection(url, userName, password);
            String sql = "select * from tab_user where name=? and pwd=?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, user.getName());
            statement.setString(2, user.getPwd());
            ResultSet resultSet = statement.executeQuery();
            if (resultSet.next()) {
                user.setAge(resultSet.getInt("age"));
                user.setBirthday(resultSet.getDate("birthday"));
                user.setDetail(resultSet.getString("detail"));
                user.setEmail(resultSet.getString("email"));
                user.setId(resultSet.getString("id"));
                user.setName(resultSet.getString("name"));
                user.setPwd(resultSet.getString("pwd"));
                user.setSex(resultSet.getInt("sex"));
            } else {
                user = null;
            }
            resultSet.close();
            statement.close();
            conn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (user != null) {
            request.removeAttribute("msg");
            request.getSession().setAttribute("user", user);
            request.getRequestDispatcher("/experiment04/index.jsp").forward(request, response);
        } else {
            request.setAttribute("msg", "用户名或密码错误");
            request.getRequestDispatcher("/experiment04/UserLogin.jsp").forward(request, response);

        }
    }
}
